﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Socium.Domain;
using Socium.Domain.Collections;
using Socium.Domain.Tests.Testings;
using Socium.Presentation;

namespace Socium.Testings {
	class TestingsIndexViewModel : PageViewModel {
		readonly Database _database;
		readonly EnvironmentService _environment_service;

		public TestingsIndexViewModel(string display_name, Database database, EnvironmentService form_view_service) : base(display_name) {
			_database = database;

			var items = database.Testings.MapLazy(CreateItem);
			_items.AddRange(items);

			NewTestingCommand = new Command(OnNewTesting);
			_environment_service = form_view_service;
		}

		TestingLineItem CreateItem(Testing testing) {
			var item = new TestingLineItem(testing);
			item.QueryEdit += model => OnItemQueryEdit(item, model);
			item.QueryDelete += model => OnItemQueryDelete(item, model);

			return item;
		}

		void OnItemQueryEdit(TestingLineItem item, Testing testing) {
			var view_model = new TestingFormViewModel(testing, _database, new DialogSelectionSource());
			view_model.ModelUpdated += item.Update;

			_environment_service.ShowForm(view_model);
		}

		void OnItemQueryDelete(TestingLineItem item, Testing testing) {
			if (_environment_service.Confirm("Dou you want to delete?")) {
				_items.Remove(item);
				_database.Testings.Remove(testing);
			}
		}

		#region Items

		readonly ObservableCollection<TestingLineItem> _items = new ObservableCollection<TestingLineItem>();

		public IEnumerable<TestingLineItem> Items {
			get { return _items; }
		}

		#endregion

		#region New item

		void OnNewTesting() {
			var view_model = new TestingFormViewModel(_database, new DialogSelectionSource());

			view_model.ModelCreated += model => {
				var item = new TestingLineItem(model);
				_database.Testings.Add(model);
				_items.Add(item);

				view_model.ModelUpdated += item.Update;
			};

			_environment_service.ShowForm(view_model);
		}

		public ICommand NewTestingCommand { get; private set; }

		#endregion
	}
}
